package com.example.imagemirrordemo

import android.graphics.Bitmap
import android.graphics.Matrix
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.drawable.toBitmap
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button1.setOnClickListener {
            imageView.setImageBitmap(toHorizontalMirror(imageView.drawable.toBitmap()))
        }
        button2.setOnClickListener {
            imageView.setImageBitmap(toVerticalMirror(imageView.drawable.toBitmap()))
        }
        button3.setOnClickListener {
            imageView.setImageBitmap(rotate(imageView.drawable.toBitmap(),30f))
        }
        button4.setOnClickListener {
            imageView.setImageBitmap(rotate(imageView.drawable.toBitmap(),90f))
        }
    }

    private fun toHorizontalMirror(bmp: Bitmap): Bitmap {
        val w = bmp.width
        val h = bmp.height
        val matrix = Matrix()
        matrix.postScale(-1f, 1f) // 水平镜像翻转
        return Bitmap.createBitmap(bmp, 0, 0, w, h, matrix, true)
    }

    private fun toVerticalMirror(bmp: Bitmap): Bitmap {
        val w = bmp.width
        val h = bmp.height
        val matrix = Matrix()
        matrix.postScale(1f, -1f) // 垂直镜像翻转
        return Bitmap.createBitmap(bmp, 0, 0, w, h, matrix, true)
    }

    private fun rotate(bmp: Bitmap, degrees: Float): Bitmap {
        val w = bmp.width
        val h = bmp.height
        val matrix = Matrix()
        matrix.postRotate(degrees)
        return Bitmap.createBitmap(bmp, 0, 0, w, h, matrix, true)
    }

}